// #include "windowmonitor.h"
// #include "ui_windowmonitor.h"
// #include <windows.h>
// #include <winuser.h>
// #include <QDebug>

// // 静态成员定义
// WindowMonitor* WindowMonitor::m_instance = nullptr;

// WindowMonitor::WindowMonitor(QWidget *parent)
//     : QMainWindow(parent)
//     , ui(new Ui::WindowMonitor)
// {
//     ui->setupUi(this);

//     m_instance = this; // 设置实例指针

//     // 可选：启动监控（也可以通过按钮触发）
//     startMonitoring();

//     // 连接信号，更新界面
//     connect(this, &WindowMonitor::activeWindowChanged, this, [this](const QString &title, quintptr windowId) {
//         ui->label_currentWindow->setText("Active Window: " + title);
//         ui->label_windowId->setText("HWND: 0x" + QString::number(windowId, 16));
//         qDebug() << "Active window changed:" << title << "| HWND:" << QString::number(windowId, 16);
//     });
// }

// WindowMonitor::~WindowMonitor()
// {
//     stopMonitoring();
//     delete ui;
// }

// void WindowMonitor::startMonitoring()
// {
//     if (m_hWinEventHook) {
//         return;
//     }

//     m_hWinEventHook = SetWinEventHook(
//         EVENT_SYSTEM_FOREGROUND,         // 监听前台窗口变化
//         EVENT_SYSTEM_FOREGROUND,
//         nullptr,
//         winEventProc,                    // 回调函数
//         0,
//         0,
//         WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS  // 允许跨线程，跳过本进程事件（可选）
//         );

//     if (!m_hWinEventHook) {
//         qWarning() << "Failed to set Windows event hook. Error:" << GetLastError();
//     } else {
//         qDebug() << "Window monitoring started.";
//     }
// }

// void WindowMonitor::stopMonitoring()
// {
//     if (m_hWinEventHook) {
//         UnhookWinEvent(m_hWinEventHook);
//         m_hWinEventHook = nullptr;
//         qDebug() << "Window monitoring stopped.";
//     }
// }

// // 静态回调函数实现
// void CALLBACK WindowMonitor::winEventProc(
//     HWINEVENTHOOK hWinEventHook,
//     DWORD event,
//     HWND hwnd,
//     LONG idObject,
//     LONG idChild,
//     DWORD dwEventThread,
//     DWORD dwmsEventTime)
// {
//     Q_UNUSED(hWinEventHook)
//     Q_UNUSED(event)
//     Q_UNUSED(idObject)
//     Q_UNUSED(idChild)
//     Q_UNUSED(dwEventThread)
//     Q_UNUSED(dwmsEventTime)

//     // 只处理主窗口
//     if (idObject != OBJID_WINDOW || !m_instance || !IsWindow(hwnd)) {
//         return;
//     }

//     char title[512] = {0};
//     int len = GetWindowTextA(hwnd, title, 512);
//     QString windowTitle = (len > 0) ? QString::fromLocal8Bit(title) : QStringLiteral("Unknown Window");

//     // 发出信号
//     emit m_instance->activeWindowChanged(windowTitle, reinterpret_cast<quintptr>(hwnd));
// }


#include "windowmonitor.h"
#include "ui_windowmonitor.h"
#include <windows.h>
#include <winuser.h>
#include <QDebug>
#include <QTimer>
#include <tlhelp32.h>
#include <psapi.h> // 需要链接 psapi.lib
#include <QFileInfo>
#include <QScrollBar>
#include <QDateTime>      // 用于时间戳
#include <QScrollBar>     // 用于自动滚动

#pragma comment(lib, "psapi.lib")

WindowMonitor* WindowMonitor::m_instance = nullptr;

WindowMonitor::WindowMonitor(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::WindowMonitor)
{
    ui->setupUi(this);
    m_instance = this;

    // 设置事件钩子
    m_hWinEventHook = SetWinEventHook(
        EVENT_SYSTEM_FOREGROUND,
        EVENT_SYSTEM_FOREGROUND,
        nullptr,
        winEventProc,
        0, 0,
        WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
        );

    if (!m_hWinEventHook) {
        qWarning() << "SetWinEventHook failed:" << GetLastError();
    }

    // 添加定时器作为备份（每500ms检查一次）
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &WindowMonitor::checkForegroundWindow);
    m_timer->start(500); // 每0.5秒检查一次
}

WindowMonitor::~WindowMonitor()
{
    if (m_hWinEventHook) {
        UnhookWinEvent(m_hWinEventHook);
    }
    delete ui;
}

void WindowMonitor::checkForegroundWindow()
{
    HWND hwnd = GetForegroundWindow();
    if (hwnd != reinterpret_cast<HWND>(m_lastHwnd)) {
        updateActiveWindow(hwnd);
    }
}

// void WindowMonitor::updateActiveWindow(HWND hwnd)
// {
//     if (!IsWindow(hwnd)) return;

//     // 过滤非主窗口
//     if (GetParent(hwnd) != nullptr || !IsWindowVisible(hwnd)) {
//         return;
//     }

//     char title[512] = {0};
//     GetWindowTextA(hwnd, title, 512);
//     QString windowTitle = QString::fromLocal8Bit(title);

//     // 获取进程名
//     DWORD pid = 0;
//     GetWindowThreadProcessId(hwnd, &pid);
//     HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
//     QString processName = "Unknown";
//     if (hProcess) {
//         char path[MAX_PATH] = {0};
//         if (GetModuleFileNameExA(hProcess, nullptr, path, MAX_PATH)) {
//             processName = QFileInfo(QString::fromLocal8Bit(path)).fileName();
//         }
//         CloseHandle(hProcess);
//     }

//     // 输出到界面和调试
//     QString msg = QString("【焦点窗口】%1 (PID: %2, Process: %3)")
//                       .arg(windowTitle).arg(pid).arg(processName);
//     qDebug().noquote() << msg;
//     ui->label_status->setText(msg);

//     // 发出信号
//     emit activeWindowChanged(windowTitle, reinterpret_cast<quintptr>(hwnd), processName);

//     m_lastHwnd = reinterpret_cast<quintptr>(hwnd);
// }

// 静态回调函数
void CALLBACK WindowMonitor::winEventProc(
    HWINEVENTHOOK hWinEventHook,
    DWORD event,
    HWND hwnd,
    LONG idObject,
    LONG idChild,
    DWORD dwEventThread,
    DWORD dwmsEventTime)
{
    if (idObject != OBJID_WINDOW || !m_instance || !IsWindow(hwnd)) {
        return;
    }

    // 直接触发更新
    m_instance->updateActiveWindow(hwnd);
}

void WindowMonitor::updateActiveWindow(HWND hwnd)
{
    if (!IsWindow(hwnd)) return;

    // 过滤非主窗口
    if (GetParent(hwnd) != nullptr || !IsWindowVisible(hwnd)) {
        return;
    }

    char title[512] = {0};
    GetWindowTextA(hwnd, title, 512);
    QString windowTitle = QString::fromLocal8Bit(title);
    if (windowTitle.isEmpty()) {
        windowTitle = QStringLiteral("No Title");
    }

    // 获取进程名
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    QString processName = "Unknown";
    if (hProcess) {
        char path[MAX_PATH] = {0};
        if (GetModuleFileNameExA(hProcess, nullptr, path, MAX_PATH)) {
            processName = QFileInfo(QString::fromLocal8Bit(path)).fileName();
        }
        CloseHandle(hProcess);
    }

    // ✅ 构造日志消息
    QString logMessage = QString("[%1] Focus → \"%2\" | HWND: 0x%3 | PID: %4 | Process: %5")
                             .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
                             .arg(windowTitle)
                             .arg(QString::number(reinterpret_cast<quintptr>(hwnd), 16))
                             .arg(pid)
                             .arg(processName);

    // ✅ 输出到调试窗口
    qDebug().noquote() << logMessage;

    // ✅ 输出到 plainTextEdit
    ui->plainTextEdit_log->appendPlainText(logMessage);

    // ✅ 自动滚动到底部
    QScrollBar *scrollBar = ui->plainTextEdit_log->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());

    // 更新状态栏或标签（可选）
    ui->label_status->setText("Active: " + windowTitle);

    // 发出信号（如果还需要）
    emit activeWindowChanged(windowTitle, reinterpret_cast<quintptr>(hwnd), processName);

    m_lastHwnd = reinterpret_cast<quintptr>(hwnd);
}
